#!/usr/bin/env node

const program = require('commander')
const inquirer = require('inquirer')
const download = require('download-git-repo')
const ora = require('ora')
const symbols = require('log-symbols')
const fs = require('fs');

const replaceStr = (str, index, char) => {
  const strAry = str.split('');
  strAry[index] = char;
  return strAry.join('');
}

program
  .version('0.0.1')
  .command('init <name>')
  .action(name => {
    if (!fs.existsSync(name)) {
      inquirer.prompt([
        {
          type: 'input',
          name: 'author',
          message: '请输入你的名字'
        },
        {
          type: 'input',
          name: 'giturl',
          message: '请输入模板地址'
        }
      ]).then((answers) => {
        let strIndex = answers.giturl.indexOf('com') + 3
        let repository =  replaceStr(answers.giturl, strIndex, ':')
        const lqProcess = ora('正在创建...')
        lqProcess.start()
        download(repository,
          name, { clone: true }, (err) => {
            if (err) {
              lqProcess.fail()
              console.log(symbols.error, err)
            } else {
              lqProcess.succeed()
              console.log(symbols.success, '创建成功')
            }
          })
      })
    } else {
      console.log(symbols.error, '项目已存在');
    }
  })

// 解析命令行的参数
program.parse(process.argv)